import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 拦截通知相关的请求
    if (config.url.includes('/notifications')) {
      // 返回一个成功的空数据响应
      return Promise.reject({
        response: {
          status: 200,
          data: {
            code: 200,
            message: 'success',
            data: {
              content: [],
              totalElements: 0
            }
          }
        },
        isNotificationRequest: true
      })
    }

    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 200) {
      return res
    }

    ElMessage.error(res.message || '请求失败')

    // token失效，跳转到登录页
    if (res.code === 401) {
      handleLogout()
    }
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  error => {
    // 如果是通知请求被拦截，返回模拟数据
    if (error.isNotificationRequest) {
      return error.response.data
    }

    console.error('响应错误:', error)

    // 未授权或token过期
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      handleLogout()
    }

    ElMessage.error(error.response?.data?.message || error.message || '请求失败')
    return Promise.reject(error)
  }
)

// 统一的登出处理
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  localStorage.removeItem('userPermissions')
  router.push('/login')
}

export default request 